package gen.tools.cra;

import gen.tools.Widgets;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mailGenerator.MailGenerator;

import org.tmatesoft.svn.core.SVNCommitInfo;
import org.tmatesoft.svn.core.SVNProperties;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNCommitClient;
import org.tmatesoft.svn.core.wc.SVNCopyClient;
import org.tmatesoft.svn.core.wc.SVNCopySource;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

public class ApproveCRA extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	
    public ApproveCRA() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		
		/*
		 * 1. 檢查這筆資料是不是還在(沒有其它主管先回覆了) 
		 * 2. 修改變更申請的狀態
		 * 4. 刪除todolist
		 * 	寄發通知信
		 * */
		
		final boolean isApprove = Integer.parseInt(request.getParameter("isApprove"))==1?true:false;	//主管是否同意
		final int craId = wid.getParNumberFromRequest( request.getParameter("craId") );	//變更申請ID
		final int toDoListId = wid.getParNumberFromRequest( request.getParameter("toDoListId") );
		final String applierId = request.getParameter("creatorId");
		final String empId = request.getParameter("empId");
		final int changeTypeId = (isApprove?9:10);
		String subsysId = "";
		
		String sql;
		String res = "NotOK";
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		//SVN抓取檔案要用
		InputStream input = null;
		ByteArrayOutputStream baos = null;
		SVNRepository cmOLrepo = null;		//SVN CM OL的Repo
		SVNRepository apSourceRepo = null;	//SVN AP Source的Repo
		
		try {
			
			conn = wid.getConn();
			
			/****檢查有沒有其它主管先回覆了****/
			sql="SELECT craStatusId,subsysId FROM cramain WHERE craId=?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, craId);
			rs = ps.executeQuery();
			rs.next();
			
			subsysId = rs.getString("subsysId");
			if ( rs.getInt(1)==8 ) {	//表示仍處於待審的狀態
				
				/****建立LOG，第一步就開始記錄程式的執行****/
				conn.setAutoCommit(false);
				sql="INSERT INTO changelog (changeLogId,changeTypeId,creatorId,bDate) VALUES (null,"+changeTypeId+",?,?)";
				ps = conn.prepareStatement(sql);
				ps.setString(1, empId);
				ps.setTimestamp(2, wid.cDT());
				ps.execute();
				sql="SELECT MAX(changeLogId) FROM changelog";
				ps = conn.prepareStatement(sql);
				rs = ps.executeQuery();
				rs.next();
				final int clId4Approve = rs.getInt(1);
				conn.commit();
				conn.setAutoCommit(true);
				
				//修改變更申請的狀態
				sql = "UPDATE cramain SET craStatusId=? WHERE craId=?";
				ps = conn.prepareStatement(sql);
				ps.setInt(1, changeTypeId);
				ps.setInt(2, craId);
				ps.execute();
				
				//取得提出者的寄件地址
				final String mailList[] = wid.getEmailAddr(applierId);
				
				
				//刪除已完成的待辦事項，將其加入待辦清單
				wid.completedList(toDoListId, applierId);
		
				String mailSubject;
				String mailBody;
				final MailGenerator mg = new MailGenerator();
				
				if ( isApprove ) {
					
					//因為同意又再分兩階段  1.簽出原始碼予開發Team(status 14)，2. 配置且成功(status 5)，故此時因為完成了1, 故又要將狀態設為5
					sql = "UPDATE cramain SET craStatusId=? WHERE craId=?";
					ps = conn.prepareStatement(sql);
					ps.setInt(1, 14);
					ps.setInt(2, craId);
					ps.execute();
					
					//將原始碼簽出到 AP 接收夾
					sql = "SELECT DISTINCT modUnitId FROM cradetail WHERE craId=?";
					ps = conn.prepareStatement(sql);
					ps.setInt(1, craId);
					rs = ps.executeQuery();
					while ( rs.next() ){
						final String modId = rs.getString("modUnitId");
						
						ISVNEditor editor = null;
						SVNCommitInfo info = null;
						final SVNProperties fileProperties = new SVNProperties();
						baos = new ByteArrayOutputStream();
						
						/*	此區開始建立SVN連線	*/
						final ArrayList<String> connCMsvnOLinfo = wid.getSVN4SubsysConnInfo(subsysId, 2);	//SVN CM OL的連線資訊
						final ArrayList<String> connAPsvnSourceinfo = wid.getSVN4SubsysConnInfo(subsysId, 5);	//SVN CM OL的連線資訊
						
						ISVNAuthenticationManager authManager = null;
						apSourceRepo = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(connAPsvnSourceinfo.get(0)));	//連線到SVN AP MR 的repo
						cmOLrepo = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(connCMsvnOLinfo.get(0)));	//連線到SVN AP OL 的repo
				        authManager = SVNWCUtil.createDefaultAuthenticationManager(connAPsvnSourceinfo.get(1), connAPsvnSourceinfo.get(2));
				        apSourceRepo.setAuthenticationManager(authManager);
				        authManager = SVNWCUtil.createDefaultAuthenticationManager(connCMsvnOLinfo.get(1), connCMsvnOLinfo.get(2));
				        cmOLrepo.setAuthenticationManager(authManager);
				        final SVNURL copyTarget = SVNURL.parseURIEncoded( connAPsvnSourceinfo.get(0)+"GG/"+modId );
				        final SVNURL copySource = SVNURL.parseURIEncoded( connCMsvnOLinfo.get(0)+modId );
				        final SVNCopySource scs = new SVNCopySource(SVNRevision.BASE,SVNRevision.BASE,copySource);
				        final SVNCopySource[] arrCS = new SVNCopySource[] {scs };
				       /* //先將該夾的內容刪除
				        final SVNCommitClient commitClient = SVNClientManager.newInstance().getCommitClient();
				        commitClient.doDelete( new SVNURL[] {copyTarget}, "");
				        
				        //然後再簽入
				        
				        final SVNCopyClient svnCopy = SVNClientManager.newInstance().getCopyClient();
				        svnCopy.doCopy(arrCS, copyTarget, false, true, false, "", fileProperties);*/
				        
				        
				        //將申請人的權限加入DB中
					}
					
					
					sql = "UPDATE cramain SET craStatusId=? WHERE craId=?";
					ps = conn.prepareStatement(sql);
					ps.setInt(1, 5);
					ps.setInt(2, craId);
					ps.execute();
				}
				
				mailSubject = mg.subjectMail(isApprove?5:6);
				mailBody = mg.mailBodyMail(isApprove?5:6, wid.getEmpName(empId));
				
				//寄發通知信
				wid.sendMailMain(mailList, mailSubject, mailBody);
				
				/****完成這次的異動****/
				sql = "UPDATE changelog SET eDate=? WHERE changeLogId=?";
				ps = conn.prepareStatement(sql);
				ps.setTimestamp(1, wid.cDT());
				ps.setInt(2, clId4Approve);
				ps.execute();
				
				res="OK";
			}
		} catch(Exception e) {
			res = wid.errProcess(e);
			wid.errLog(e);
		} finally {
			try {
				if ( baos !=null ) {baos.close();}
				if ( input !=null ) {input.close();}
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
				if ( apSourceRepo != null ) { apSourceRepo.closeSession(); }
				if ( cmOLrepo != null ) { cmOLrepo.closeSession(); }
			} catch (Exception e) { e.printStackTrace(); }
		}
		response.getWriter().write( res );
	}
}
